/**
 *  @fileOverview  BDB background script.
 */

// Backup module:
// If there is no config setting in localStorage,
// check file system.
if ( typeof localStorage['__BDB_configSetting__'] === 'undefined' ) {
	$.FileSys.read( 'BDB_configSetting.log', {
		success : function( data ) {
			if ( data )  {
				localStorage['__BDB_configSetting__'] = data;
				localStorage['__BDB_lastModified__'] = 1;
			}
		},
		error: function() {
			// Suppose it is a first run.
			// Open the option page.
			localStorage['__BDB_configSetting__'] = JSON.stringify(ConfigContent.defaultSetting);
			open( "bg-page/option-page/main.html" );
		}
	});
}
if ( typeof localStorage['__BDB_lastModified__'] === 'undefined' ) {
	localStorage['__BDB_lastModified__'] = 1;
}

// CSS control module:
var CSS_Set = {
	'user-defined' : '',
	'hidden' : '',
	'all' : ''
};
(function( array ) {
	'use strict';
	for ( var i = array.length, item, path; i--; ) {
		item = array[i];
		path = '/css-set/' + item + '.css';
		$.Ajax.get( path, {
			success: function(t){ CSS_Set[item] = t.replace(/[\n\r ]+/g, ' '); supplyCSS_Set(); },
			error : function(){ CSS_Set[item] = ''; console.log(' Get '+item+'.css failed! '); }
		});
	}
})( ['bdb-common'] );
$.addEventHandler( 'f-setting-update', supplyCSS_Set );

function supplyCSS_Set() {
	'use strict';
	CSS_Set['user-defined'] = decodeURI( Config.get( 'userCSSEditor' ) );

	var cssHideSelectors = [];
	// Loop in Hide module.
	var displayGroupMain = ConfigContent.displayGroup.main;
	for ( var key in displayGroupMain ) {
		if ( Config.get(key) ) {
			cssHideSelectors.push( displayGroupMain[key]['selector'] );
		}
	}

	if ( cssHideSelectors.length )
		CSS_Set['hidden'] = cssHideSelectors.join(',') + '{display:none!important}';
	else
		CSS_Set['hidden'] = '';

	// Gether them all.
	CSS_Set['all'] = '';
	if ( Config.get( 'theme-style' ) )
		CSS_Set['all'] += CSS_Set['bdb-common'];
	CSS_Set['all'] += '\n' + CSS_Set['hidden'];
	if ( Config.get( 'userCSS' ) ) //// Put user-defined CSS at last cuz user may write it broken;
		CSS_Set['all'] += '\n' + CSS_Set['user-defined'];

}


// Referrer control module:
var refTable = {
	'baidu.com' : '',
	'126.net' : '',
	'pic.sogou.com' : '',
	'sinaimg.cn' : ''
}, tabs = { __proto__: null };
$c.hasPerm({
		origins: refOrigins,
		permissions: refPermissions
	}, function(r) {
		r && initRefControl();
});
$.addEventHandler( 'b-setting-update', initRefControl );

function initRefControl() {
	if ( chrome.webRequest.onBeforeSendHeaders.hasListeners() || chrome.webRequest.onSendHeaders.hasListeners() )
		return;

	if ( Config.get('refControl') ) {
		chrome.webRequest.onBeforeSendHeaders.addListener( refControl, {
			urls : refOrigins,
			types : [ "image" ]
		}, ['requestHeaders', 'blocking'] );
		chrome.webRequest.onSendHeaders.addListener( recordTab, {
			urls : [ "http://tieba.baidu.com/*" ],
			types : [ "main_frame" ]
		} );
	}

	if ( chrome.tabs.onRemoved.hasListeners() === false )
		chrome.tabs.onRemoved.addListener( forgetTab );

	// For the future.
	chrome.permissions.onRemoved.addListener(function( removedPermission ) {
		removedOrigins = removedPermission.origins;
		if ( removedOrigins.contains(refOrigins[1]) ) {
			chrome.webRequest.onBeforeSendHeaders.removeListener( refControl );
		}
		if ( removedOrigins.contains(refOrigins[0]) ) {
			chrome.webRequest.onSendHeaders.removeListener( recordTab );
		}
	});
}
function recordTab( details ) {
	"use strict";
	if ( !Config.get( 'refControl' ) )
		return;
	var url = details.url, tabId = details.tabId, requestHost = extractDomain( url );
	if ( requestHost.indexOf( 'baidu.com' ) > -1 )
		tabs[tabId] = requestHost;
	else if ( typeof tabs[tabId] !== 'undefined' )
		delete tabs[tabId];
}
function forgetTab( tabId ) {
	if ( typeof tabs[tabId] !== 'undefined' )
		delete tabs[tabId];
}
function refControl( details ) {
	"use strict";
	if ( !Config.get( 'refControl' ) )
		return;
	var url = details.url, tabId = details.tabId, requestHost = extractDomain(url);

	var key;
	if ( /\W(126\.net|sinaimg\.cn)/i.test(requestHost) && tabs[tabId] === 'tieba.baidu.com' )
		key = RegExp.$1;
	else if ( requestHost.indexOf( 'baidu.com' ) > -1 )
		key = 'baidu.com';
	else
		return;

    var headers = details.requestHeaders || [];
	for ( var i = headers.length; i--; ) {
		if ( headers[i].name === 'Referer' ) {
			if ( typeof refTable[key] !== 'undefined' ) {
				if ( refTable[key] === '' )
					headers.splice( i, 1 );
				else
					headers[i].value = refTable[key];
			}
			break;
		}
	}
    return { requestHeaders: headers };
}
function extractDomain( url ) {
	"use strict";
	if ( !url ) return '';
	url = url.substr(3 + url.indexOf('://'));
	return url.substr(0, url.indexOf('/'));
}


// Communicate module.
$c.onRequest( function( msg, sender, Response ) {
	if ( msg.hostname ) { // the message comes from a content script.
		if ( msg.hostname === 'tieba.baidu.com' ) {
			var ret = {
				'setting' : localStorage['__BDB_configSetting__'],
				'settingMain' : Config.getConfigSettingMain(),
				// Often the case, the setting is not changed at all. So we can response a 304 status.
				'status' : (+msg.ifModifiedSince >= +localStorage['__BDB_lastModified__']) ? 304 : 200,
				'mainCSS' : CSS_Set['all']
			};
			Response(ret);
		} else {
			var tabId = sender.tab.id;
			if ( typeof tabs[tabId] !== 'undefined' )
				delete tabs[tabId];
		}
	} else if (msg.event) { // the message comes from option-page.
		$.fireEvent( msg.event, msg.info );
	}
});


// Context menu control module:
initContextMenu();
$.addEventHandler( 'b-setting-update', initContextMenu );
function initContextMenu() {
	"use strict";
	$c.removeAllMenus( removeAllCallBack );
}
function removeAllCallBack() {
	if ( Config.get( 'tb_search' ) ) {
		$c.addMenu({
			'title' : '百度贴吧搜索',
			'contexts' : [ 'selection' ],
			'onclick' : function(info, tab) {
				var e = encodeURIComponent;
				var selectText = info.selectionText || '';
				open( 'http://tieba.baidu.com/f?ie=utf-8&kw=' + e( selectText ) );
			}
		});
	}
	if ( Config.get( 'pic_search' ) ) {
		switch ( Config.get( 'image-search-engine' ).toLowerCase() ) {
			case 'baidu':
				$c.addMenu({
					'title' : '百度图片搜索',
					'contexts' : [ 'selection' ],
					'onclick' : function( info, tab ) {
						var e = encodeURIComponent;
						var selectText = info.selectionText || '';
						open( 'http://image.baidu.com/i?ie=utf-8&word=' + e( selectText ) );
					}
				});
				$c.addMenu({
					'title' : '百度识图',
					'contexts' : [ 'image' ],
					'onclick' : function( info, tab ) {
						var e = encodeURIComponent;
						open('http://stu.baidu.com/i?objurl=' + e(info['srcUrl']) + '&rt=0&rn=10&ftn=searchstu&ct=1&tn=baiduimage');
					}
				});
				break;
			case 'google':
				$c.addMenu({
					'title' : 'Google图片搜索',
					'contexts' : [ 'selection' ],
					'onclick' : function( info, tab ) {
						var e = encodeURIComponent;
						var selectText = info.selectionText || '';
						open( 'https://www.google.com/search?tbm=isch&q=' + e(selectText) );
					}
				});
				$c.addMenu({
					'title' : 'Google similar image search',
					'contexts' : [ 'image' ],
					'onclick' : function( info, tab ) {
						var e = encodeURIComponent;
						open( 'https://www.google.com/searchbyimage?image_url=' + e(info['srcUrl']) );
					}
				});
				break;
		}
	}
	if ( Config.get( 'i_share' ) ) {
		$c.addMenu({
			'title' : '分享此页至 I 贴吧',
			'documentUrlPatterns' : [ "http://*/*", "https://*/*", "ftp://*/*" ],
			'onclick' : function( info, tab ) {
				var e = encodeURIComponent;
				var location = info.pageUrl;
				open( 'http://tieba.baidu.com/i/app/open_share_api?link=' + e(location) );
			}
		});
	}
	if ( Config.get( 'du_cang' ) ) {
		$c.addMenu({
			'title' : '添加此页至百度搜藏',
			'documentUrlPatterns' : [ "http://*/*", "https://*/*", "ftp://*/*" ],
			//'contexts' : [ 'page', 'selection' ],
			'onclick' : function( info, tab ) {
				var e = encodeURIComponent;
				var location = info.pageUrl;
				var title = tab.title || '';
				var description = info.selectionText || '';
				open( 'http://cang.baidu.com/do/add?it=' + e(title) + '&iu=' + e(location) + '&dc=' + e(description) + '&fr=ien#nw=1' );
			}
		});
	}
}

